<?php
ob_start();
session_start();
require 'facebook.php';
require 'model/fbconfig.php';
require 'model/functions.php';
include("model/xl_nguoi_dung.php");

$xl_nguoi_dung = new xl_nguoi_dung();

$facebook = new Facebook(array(
            'appId' => APP_ID,
            'secret' => APP_SECRET,
        ));

$session = $facebook->getSession();

if (!empty($session)) {
    try {
        $uid = $facebook->getUser();
        $user = $facebook->api('/me');
    } catch (Exception $e) {
    }
    if (!empty($user)) {
        $username = $user['name'];
		$mail = $user['email'];
		$usr = $xl_nguoi_dung->layNguoiDungTheoEmail($mail);
		$row1 = $usr[0];
		if(count($usr)>0 && $row1['oauth_provider']==!'facebook')
		{
			header("Location: ./?action=login-facebook-google-fail");
		}
		else{
			$user = new User();
			$userdata = $user->checkUser($uid, 'facebook', $username,$mail);
			$row = $userdata[0];
			if(!empty($userdata)){
				$_SESSION['usid'] = $row['MaNguoiDung'];
				$_SESSION['oauth_id'] = $uid;
				$_SESSION['email'] = $row['Email'];
				$_SESSION['fullname'] = $row['TenHienThi'];
				$_SESSION['ava'] = $row['HinhAnhDaiDien'];
				$_SESSION['oauth'] = $row['oauth_provider'];
				header("Location: ./");
			}
		}
    } else {
        die("There was an error.");
    }
} else {
    $login_url = $facebook->getLoginUrl(array('req_perms' => 'email'));
    header("Location: " . $login_url);
}
?>
